package com.suemi.missile.common.entity;


import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;

public class ESDocument implements Documentable {

  private String documentId;

  private Patent patent;

  private String lastModified; // 最后一次更改的时间

  private String submitAt; // 提交到ES的时间

  @Override
  public void fromJson(JSONObject json) {
    patent = new Patent();
    patent.fromJson(json);
  }

  @Override
  public JSONObject toJson() {
    JSONObject json = patent == null ? new JSONObject() : patent.toJson();
    return json;
  }


  @Override
  public String documentId() {
    return documentId;
  }

  public void setDocumentId(String id) {
    documentId = id;
  }

  public Patent getPatent() {
    return patent;
  }

  public void setPatent(Patent patent) {
    this.patent = patent;
  }

  @Deprecated
  public static JSONObject genIndexMapping() {
    JSONObject props = new JSONObject();
    for (Field field : Patent.class.getDeclaredFields()) {
      props.put(field.getName(), new JSONObject(new HashMap<String, Object>() {
        {
          put("store", "yes");
          put("type", "string");
        }
      }));
    }
    JSONObject mappings = new JSONObject();
    mappings.put("properties", props);
    return mappings;
  }

  @SuppressWarnings("uncheck")
  @Override
  public <T> T getField(String name) {

    Field field = null;
    Object obj = null;
    try {
      field = this.getClass().getDeclaredField(name);
      obj = this;
    } catch (NoSuchFieldException err) {
      field = null;
      obj = null;
    }

    if(field == null && patent!=null) {
      return patent.getField(name);
    }

    try {
      field.setAccessible(true);
      return (T) field.get(obj);
    } catch (IllegalAccessException e) {
      return null;
    }

  }

  @Override
  public List<String> fieldNames() {
    Patent tmp = patent == null? new Patent() : patent;
    List<String> subNames = tmp.fieldNames();
    List<String> names = tmp.fieldNames();
    names.remove("patent");
    names.addAll(subNames);
    return names;
  }
}
